package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
@CrossOrigin
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "thumbup/{id}",method = RequestMethod.PUT)
    public Result thumbup(@PathVariable String id){

        String userId = "123";
        Object o = redisTemplate.opsForValue().get("thumbup_" + userId + "_" + id);
        if (o!=null){
            return new Result(false,StatusCode.OK,"不允许点赞");
        }
        redisTemplate.opsForValue().set("thumbup_" + userId + "_" + id,1);
        commentService.thumbup(id);
        return new Result(true,StatusCode.OK,"点赞成功");
    }

    @RequestMapping(value = "/articleId",method = RequestMethod.GET)
    public Result findByArticleId(@PathVariable String articleId){
        List<Comment> commentList = commentService.findByArticleId(articleId);
        return new Result(true, StatusCode.OK,"查询成功",commentList);
    }

    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        List<Comment> commentList = commentService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",commentList);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable String id){
        Comment comment = commentService.findById(id);
        return new Result(true, StatusCode.OK,"查询成功",comment);
    }

    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Comment comment){
        commentService.add(comment);
        return new Result(true,StatusCode.OK,"新增成功");
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public Result update(@PathVariable String id,
                         @RequestBody Comment comment){
        comment.set_id(id);
        commentService.update(comment);
        return  new Result(true,StatusCode.OK,"修改成功");
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id){
        commentService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

}
